package cn.qingyun.gis.modules.alongstreet.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.qingyun.gis.modules.alongstreet.entity.BusinessBoundary;
import cn.qingyun.gis.modules.alongstreet.mapper.BusinessBoundaryMapper;
import cn.qingyun.gis.modules.alongstreet.request.BusinessRequest;
import cn.qingyun.gis.modules.alongstreet.response.BusinessResponse;
import cn.qingyun.gis.modules.alongstreet.service.IBusinessBoundaryService;
import cn.qingyun.gis.modules.init.system.constant.enums.RegionNumPermissionEnum;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 商圈边界 服务实现类
 * </p>
 *
 * @author guest
 * @since 2024-03-20
 */
@DS("mysql-build")
@Service
public class BusinessBoundaryServiceImpl extends ServiceImpl<BusinessBoundaryMapper, BusinessBoundary> implements IBusinessBoundaryService {


    @SneakyThrows
    @Override
    public List<BusinessResponse> queryByParam(BusinessRequest request) {

        QueryWrapper<BusinessBoundary> queryWrapper = new QueryWrapper<>();

        String keyword = request.getKeyword();
        if (CharSequenceUtil.isNotEmpty(keyword)) {
            queryWrapper.lambda().and(
                    qw -> qw.like(BusinessBoundary::getBusinessName, keyword)
                            .or()
                            .like(BusinessBoundary::getCentAddress, keyword)
            );
        }

        queryWrapper.lambda().eq(BusinessBoundary::getAuditStatus, 4); // 质检通过
        queryWrapper.lambda().eq(BusinessBoundary::getQualified, 1); // 合格
        queryWrapper.lambda().last("and wkt is not null and ST_isValid(ST_GeomFromText(wkt))"); // 筛选边界有效

        if (ObjectUtil.isNotEmpty(request.getGridIds())) {
            List<String> gridList = Arrays.asList(request.getGridIds().split(","));
            // 若为省级工号
            if (RegionNumPermissionEnum.PROVINCE.name().equals(request.getGridType()) && "SD".equals(request.getGridIds())) {
                return BeanUtil.copyToList(this.list(queryWrapper), BusinessResponse.class);
            }
            queryWrapper.lambda().and(
                    wp -> wp.in(BusinessBoundary::getRegionCityCode, gridList).
                            or().
                            in(BusinessBoundary::getRegionDistrictsCode, gridList).
                            or().
                            in(BusinessBoundary::getGirdId, gridList)
            );
            return BeanUtil.copyToList(this.list(queryWrapper), BusinessResponse.class);
        }
        return Lists.newArrayList();

    }
}
